<?PHP

$user = $_REQUEST['username'];
$identity = $_REQUEST['identity'];
$friends = $_REQUEST['friends'];

header('Content-type: text/plain');

$projectfolder = '../../../';
// include configuration
include $projectfolder . 'config.php';
// include db
include $projectfolder . 'apps/common/lib/class.db.php';

// open db connection
db::connect();

echo '<?xml version="1.0" encoding="utf-8"?>'."\n".'<result>'."\n";

if($user){
    db::query(sprintf("INSERT INTO chatUsers (username, identity, updatetime)
        VALUES (%d, '%s', NOW())
        ON DUPLICATE KEY UPDATE identity = '%s', updatetime = NOW()",
            $user, $identity, $identity));

    echo "\t<update>true</update>\n";
} else {
    $friends = is_array($friends) ? $friends : array($friends);
    foreach ($friends as $f){
        echo "\t<friend>\n\t\t<user>".$f."</user>\n";
        $f = db::query(sprintf("SELECT username, identity FROM chatUsers
            WHERE username = %d AND updatetime > (NOW()-3600)", $f), true);
        echo "\t\t<identity>".$f->identity."</identity>\n";
        echo "\t</friend>\n";
    }
}

echo '</result>';

// close db connection
db::disconnect();

?>
